<?php


namespace app\api\controller;

/*
 * 聊天室会员接口
 */

use addons\shopro\model\User;
use app\admin\model\general\VipConfig;
use app\admin\model\order\AppManage;
use app\admin\model\share\ShareUser;
use app\common\controller\Api;
use app\common\model\MoneyLog;
use think\Db;
use think\Request;

class Vip extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //是否会员
    public function is_vip()
    {
        $is_vip = $this->auth->__get('is_vip');
        $exp_time = $this->auth->__get('vip_exp_time');
        if ($is_vip && ($exp_time < time())) {
            $this->error('会员已过期', ['is_vip' => 3]);
        }
        $this->success('获取成功', ['is_vip' => $is_vip]);
    }

    //单聊，群聊创建鉴权
    public function chat_create_check()
    {
        $chat_type = $this->request->post("chat_type");
        $is_vip = $this->auth->__get('is_vip');
        $exp_time = $this->auth->__get('vip_exp_time');
        $uid = $this->auth->id;

        //群聊
        if ($chat_type == "group") {
            if (!$is_vip || ($exp_time < time())) {
                $this->error('仅需一步升级会员，就可以建立群聊', '', 4031);
            }
            $map = [
                'user_id' => $uid,
                'chat_type' => 2
            ];
            $vip_grp_limit = Db::name("config")->where(['name' => 'vip_grp_limit'])->value('value');
            $svip_grp_limit = Db::name("config")->where(['name' => 'svip_grp_limit'])->value('value');
            $limit = ($is_vip == 1) ? $vip_grp_limit : $svip_grp_limit;
            $group_count = Db::name('chat_create_log')->where($map)->count();
            if ($group_count >= $limit) {
                $this->error('仅需一步升级会员，就可以建立群聊', '', 4031);
            }
        }

        //单聊
        if ($chat_type == "single") {
            switch ($is_vip) {
                case 0:
                    $limit = Db::name("config")->where(['name' => 'user_sig_limit'])->value('value');
                    break;
                case 1:
                    $limit = Db::name("config")->where(['name' => 'vip_sig_limit'])->value('value');
                    break;
                case 2:
                    $limit = Db::name("config")->where(['name' => 'svip_sig_limit'])->value('value');
                    break;
                default:
                    $limit = Db::name("config")->where(['name' => 'user_sig_limit'])->value('value');
            }

            if ($is_vip && ($exp_time < time())) {
                //会员过期 按照普通用户
                $limit = Db::name("config")->where(['name' => 'user_sig_limit'])->value('value');
            }
            $map = [
                'user_id' => $uid,
                'chat_type' => 1
            ];
            $single_count = Db::name('chat_create_log')->where($map)->count();
            if ($single_count >= $limit) {
                $this->error('仅需升级会员，就可以和更多人聊天', '', 4031);
            }
        }
        $this->success('鉴权成功');
    }

    //存储聊天发起记录
    public function chat_log()
    {
        $chat_type = $this->request->post("chat_type");
        $chat_obj = $this->request->post("chat_obj");
        $is_vip = $this->auth->__get('is_vip');
        $exp_time = $this->auth->__get('vip_exp_time');
        $uid = $this->auth->id;
        if (empty($chat_type) || empty($chat_obj)) {
            $this->error('参数错误');
        }
        if ((!$is_vip || ($exp_time < time())) && $chat_type == 2) {
            $this->error('非会员无法发起群聊', '', 4031);
        }
        $data = [
            'user_id' => $uid,
            'chat_obj' => $chat_obj,
            'chat_type' => $chat_type,
            'create_time' => time()
        ];
        $map = [
            'user_id' => $uid,
            'chat_obj' => $chat_obj,
        ];
        $res = Db::name('chat_create_log')->where($map)->count();
        if (!$res) {
            //同一用户，同一聊天对象只存储一次
            Db::name('chat_create_log')->insert($data);
        }
        $this->success('记录存储成功');
    }

    //群聊鉴权接口
    public function group_check()
    {
        $chat_obj = $this->request->post("chat_obj");
        if (empty($chat_obj)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $map = [
            'chat_obj' => $chat_obj,
            'chat_type' => 2
        ];
        $res = Db::name('chat_create_log')->where($map)->find();
        if (!$res) {
            $this->error('未找到该群聊的发起记录');
        }
        $master = Db::name('user')->where("id", $res['user_id'])->find();
        if ($master['vip_exp_time'] < time()) {
            if ($res['user_id'] == $uid) {
                $this->error('您的会员身份已到期，该群聊暂时关闭。');
            }
            $this->error('由于群聊创建者会员身份到期，该群聊暂时关闭');
        }
        $this->success('群聊授权成功');
    }

    //到期提醒内容
    public function exp_notice()
    {
        $is_vip = $this->auth->__get('is_vip');
        $data = false;
        if ($is_vip) {
            $exp_time = $this->auth->__get('vip_exp_time');
            $s = strtotime(date('Y-m-d') . '00:00:00');
            $l = strtotime(date('Y-m-d') . '23:59:59');
            if (($exp_time > $s) && ($exp_time < $l)) {
                //当天到期提醒
                $exp_time = datetime($exp_time, "H:i:s");
                $str = Db::name("config")->where(['name' => 'today_notice'])->value('value');
                $data = preg_replace("/\{.*\}/", $exp_time, $str);
            } elseif (($exp_time - time()) < 86400 * 3) {
                //三天到期提醒
                $exp_time = datetime($exp_time, "m月d日 H:i:s");
                $str = Db::name("config")->where(['name' => 'pre_notice'])->value('value');
                $data = preg_replace("/\{.*\}/", $exp_time, $str);
            }
        }
        $this->success('请求成功', $data);
    }

    //会员权益介绍
    public function desc()
    {
        $data = Db::name("config")->where(['name' => 'vip_desc'])->value('value');
        $this->success("获取成功", $data);
    }

    //会员配置明细
    public function list()
    {
        $vip_type = $this->request->post('vip_type', 0);//0=会员版 1=升级版
        $is_vip = $this->auth->__get('is_vip');
        if ($is_vip) {
            $exp_time = $this->auth->__get('vip_exp_time');
            $vip_days = $this->auth->__get('vip_days');
            $exp_time_txt = datetime($exp_time, "Y年m月d日");
        }
        $list = Db::name('vip_config')->where('vip_type', $vip_type)->order('price', 'asc')->select();
        $old_map = [
            'user_id' => $this->auth->id,
            'pay_status' => 2
        ];
        $is_old = Db::name('vip_recharge_order')->where($old_map)->count();
        $vip_sig_limit = Db::name("config")->where(['name' => 'vip_sig_limit'])->value('value');
        $svip_grp_limit = Db::name("config")->where(['name' => 'svip_grp_limit'])->value('value');
        $vip_grp_limit = Db::name("config")->where(['name' => 'vip_grp_limit'])->value('value');

        foreach ($list as $key => $value) {
            //支付完成任何一单，则不能再享受新用户7天试用。
            if ($is_old && $value['is_trial']) {
                unset($list[$key]);
                continue;
            }
            $list[$key]['sub_price'] = bcsub($value['origin_price'], $value['price'], 0);
            $list[$key]['single'] = $value['vip_type'] ? null : $vip_sig_limit;
            $list[$key]['group'] = $value['vip_type'] ? $svip_grp_limit : $vip_grp_limit;
            $list[$key]['enable'] = true;
            $list[$key]['jianmian'] = 0;
            if (($is_vip == 1) && ($vip_type == 1) && ($exp_time > time())) {

                //会员转升级
                $list[$key]['enable'] = false;
                /* if ($value['valid_day'] != $vip_days) {
                     //非对应天数不能选择
                     $list[$key]['enable'] = false;
                 } else {
                     $exp_day = strtotime(datetime($exp_time, "Y-m-d"));
                     $today = strtotime(datetime(time(), "Y-m-d"));
                     $sy_day_sum = round(($exp_day - $today) / 86400, 0);
                     $current = Db::name('vip_recharge_order')
                         ->where('user_id', $this->auth->id)
                         ->where('pay_status', 2)
                         ->where('type', ['=', 1], ['=', 4], 'or')
                         ->select();
                     foreach ($current as $ck => $cv) {
                         //使用天数
                         $use_day = ($today - strtotime(datetime($cv["pay_time"], "Y-m-d"))) / 86400;
                         //剩余天数
                         $sy_day = $cv["expdays"] - $use_day;
                         //剩余费用
                         if ($sy_day > 0) {
                             $list[$key]['jianmian'] += bcdiv($cv['pay_money'], $cv['expdays'], 2) * $sy_day;
                         }
                     }
                     //转升级应付的钱
                     $yf_money = bcdiv($value['price'], $value['valid_day'], 2) * $sy_day_sum;
                     //转升级减免后应付的钱
                     $list[$key]['price'] = bcsub($yf_money, $list[$key]['jianmian'], 2);
                     $list[$key]['sub_price'] = bcsub($value['origin_price'], $list[$key]['price'], 0);
                 }*/
            }
            if (($is_vip == 2) && ($exp_time > time()) && ($vip_type == 0)) {
                //当前是升级版会员，普通会员下所有套餐不能选择
                $list[$key]['enable'] = false;
            }
        }
        $data = [
            "user_level" => $is_vip,
            'exp_time' => isset($exp_time_txt) ? $exp_time_txt : null,
            'list' => array_values($list)
        ];
        $this->success("获取成功", $data);
    }

    //创建订单
    public function create_order()
    {
        $vip_item_id = $this->request->post('vip_item_id');
        $vip_item = VipConfig::where('id', $vip_item_id)->find();
        $uid = $this->auth->id;
        if (!$vip_item) {
            $this->error("参数错误");
        }
        if (!$this->session_check_new($this->request->ip(), 10)) {
            $this->error('请勿重复提交');
        }
        $old_map = [
            'user_id' => $this->auth->id,
            'pay_status' => 2
        ];
        $is_old = Db::name('vip_recharge_order')->where($old_map)->count();
        //支付完成任何一单，则不能再享受新用户7天试用。
        if ($is_old && $vip_item['is_trial']) {
            $this->error("非新用户无试用机会");
        }
        try {
            Db::transaction(function () use ($vip_item, $uid, &$order_id) {
                $user = User::lock(true)->find($uid);
                $price = $vip_item->price;
                $order_type = ($vip_item->vip_type) ? 2 : 1;//2升级版 1会员版

                if (($user->is_vip == 2) && ($vip_item->vip_type == 0)) {
                    //当前是升级版会员，普通会员下所有套餐不能选择
                    throw new \Exception('当前是升级版会员,无法购买普通会员');
                }
                if ($user->is_vip == 1) {
                    $order_type = 4; //续费会员
                }
                if ($user->is_vip == 2) {
                    $order_type = 5; //续费升级版会员
                }

                if (($user->is_vip == 1) && ($vip_item->vip_type == 1)) {
                    //当前是升级版会员，普通会员下所有套餐不能选择
                    throw new \Exception('系统维护中，暂不能转升级会员');
                    //普通会员转升级版
                    $order_type = 3; //补差价
                    $exp_time = $this->auth->__get('vip_exp_time');
                    $vip_days = $this->auth->__get('vip_days');
                    if ($vip_item->valid_day != $vip_days) {
                        //当前是普通会员，升级版时只能选择对应天数的期限规格
                        throw new \Exception('该规格不能购买');
                    }
                    $map = [
                        'user_id' => $this->auth->id,
                        'type' => 1,
                    ];
                    $current = Db::name('vip_recharge_order')->where($map)->order('id', "desc")->find();
                    $exp_day = strtotime(datetime($exp_time, "Y-m-d"));
                    $today = strtotime(datetime(time(), "Y-m-d"));
                    $sy_day = round(($exp_day - $today) / 86400, 0);
                    $jianmian = round(bcdiv($current['pay_money'], $current['expdays'], 2) * $sy_day, 0);
                    $item_price = round(bcdiv($vip_item->price, $vip_item->valid_day, 2) * $sy_day, 0);
                    //需付费用
                    $vip_item->price = bcsub($item_price, $jianmian, 0);
                }


                //会员充值订单
                $now_time = time();
                $order = [
                    "user_id" => $uid,
                    "origin_price" => $vip_item->origin_price,
                    "price" => $price,
                    "type" => $order_type,
                    "expdays" => $vip_item->valid_day,
                    "pay_money" => $vip_item->price,
                    "pay_type" => 1,
                    "pay_status" => 1,
                    "createtime" => $now_time,
                    "updatetime" => $now_time,
                ];
                $ignore_map = [
                    'user_id' => $uid,
                    'pay_status' => 1,
                    'is_notice' => 1
                ];
                //忽略之前所有待支付订单
                Db::name('vip_recharge_order')->where($ignore_map)->update(['is_notice' => 2]);
                $order_id = Db::name('vip_recharge_order')->insertGetId($order);
            });
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('订单创建成功', ['order_id' => $order_id]);
    }

    // 余额支付
    public function wallet_pay()
    {
        $order_id = $this->request->post('order_id');
        $order = Db::name('vip_recharge_order')->where('id', $order_id)->find();
        if (!$order) {
            $this->error('该订单不存在');
        }
        $share_user = ShareUser::where(['is_delete' => 0, 'user_id' => $order['user_id']])->find();
        if (!$share_user) {
            $this->error('该用户已删除');
        }
        try {
            Db::transaction(function () use ($order, $share_user) {
                if ($share_user->price - $order['pay_money'] < 0) {
                    throw new \Exception('可用余额不足');
                }
                if ($order['pay_status'] == 2) {
                    throw new \Exception('该订单已支付，请勿重复操作');
                }
                $user = User::lock(true)->find($order['user_id']);
                //is_vip:0=否,1=普通会员,2=升级版会员
                $user->vip_days = $order['expdays'];
                if ($order['type'] == 3) {
                    throw new \Exception('系统维护中，暂不能转升级会员');
                    if ($user->vip_exp_time < time()) {
                        //已过期有效期从当前算起
                        $user->vip_exp_time = time() + $order['expdays'] * 86400;
                    }
                    //vip_type:会员类型:0=会员版,1=升级版
                    $user->is_vip = 2;
                    $memo = "升级补差价";
                } elseif ($order['type'] == 4) {
                    if ($user->vip_exp_time < time()) {
                        //已过期有效期从当前算起
                        $user->vip_exp_time = time() + $order['expdays'] * 86400;
                    } else {
                        $user->vip_exp_time += $order['expdays'] * 86400;
                    }
                    $memo = "会员续费";
                } elseif ($order['type'] == 5) {
                    if ($user->vip_exp_time < time()) {
                        //已过期有效期从当前算起
                        $user->vip_exp_time = time() + $order['expdays'] * 86400;
                    } else {
                        $user->vip_exp_time += $order['expdays'] * 86400;
                    }
                    $memo = "升级版续费";
                } else {
                    //开通
                    $user->vip_open_date = time();
                    $user->vip_exp_time = time() + $order['expdays'] * 86400;
                    $user->is_vip = $order['type'];
                    $memo = "开通会员";
                }
                //更新会员信息
                $user->save();

                //变更日志
                MoneyLog::create(['user_id' => $order['user_id'], 'money' => $order['pay_money'], 'before' => $share_user->price, 'after' => $share_user->price - $order['pay_money'], 'type' => 14, 'memo' => $memo, 'order_id' => $order['id']]);

                //扣除余额
                ShareUser::where(['is_delete' => 0, 'user_id' => $order['user_id']])->setDec('price', $order['pay_money']);

                //更新订单状态
                Db::name('vip_recharge_order')->where('id', $order['id'])->update(['pay_status' => 2, "pay_time" => time(), 'remark' => $memo]);
            });
        } catch (\Exception $e) {
            $this->error("支付失败:" . $e->getMessage());
        }
        $this->success('支付成功');
    }

    /*
     * 待支付提醒接口
     */
    public function pay_notice()
    {
        $action = $this->request->post('action', 'get');
        $map = [
            'user_id' => $this->auth->id,
            'pay_status' => 1,
            'is_notice' => 1,
            'createtime' => ['>', time() - 1800]
        ];
        if ($action == "ignore") {
            $res = Db::name('vip_recharge_order')->where($map)->update(['is_notice' => 2]);
            if ($res) {
                $this->success('忽略成功');
            } else {
                $this->error('操作失败：无待支付订单');
            }
        }
        $order = Db::name('vip_recharge_order')->where($map)->order('id', 'desc')->field('id,user_id,type,expdays,pay_money,origin_price')->find();
        if ($order) {
            $time_txt = [
                "7" => "7天",
                "30" => "一个月",
                "90" => "三个月",
                "360" => "12个月"
            ];
            $order['expdays'] = $time_txt[$order['expdays']];
        }
        $is_notice = $order ? true : false;
        $this->success('请求成功', ["is_notice" => $is_notice, "order" => $order]);
    }

//防止频繁操作
    public function session_check_new($ip, $miao = 10)
    {
        session_start();
        $key = md5($_SERVER['REQUEST_URI']);
        if (isset($_SESSION[$ip][$key])) {
            $requestSec = time() - $_SESSION[$ip][$key];
            if ($requestSec < $miao) {
                return false;
            } else {
                $_SESSION[$ip][$key] = time();
            }
        } else {
            $_SESSION[$ip][$key] = time();
        }
        return true;
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 通讯录
     */
    public function reFriend(){
        $mobels = $this->request->post('mobels');
        if(!$mobels){
            $this->error('缺少必传参数');
        }
        $arr_mobile = [];
        if (strpos($mobels,',') == false) {
            $arr_mobile[0] = $mobels;
        }else{
            $arr_mobile =  explode(",",$mobels);
        }
        $f_user_id = $this->auth->id;
        $re_data1 = [];
        $re_data = [];
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $update_url = Db::name("config")->where(['name' => 'update_url'])->value('value');
        $app_id = (new AppManage())->getAppId($url['value']);
        foreach ($arr_mobile as $k=>$v){
            $user_data = Db::name("user")->where(['mobile'=>$v])->find();
            if($user_data){
                $re_data['u_status'] = 1;
                $friends_data = Db::name("user_friends")->where(['user_id'=>$f_user_id,'f_uid'=>$user_data['id'],'relation'=>1])->find();
                if($friends_data){
                    $re_data['f_status'] = 1;
                }else{
                    $re_data['f_status'] = 0;
                }
                $re_data['user_id'] = $user_data['id'];
            }else{
                $re_data['u_status'] = 2;
                $re_data['f_status'] = 2;
                $re_data['user_id'] = 0;
            }
            $re_data['app_id'] = $app_id['id'];
            $re_data1[] = $re_data;
        }
        $re_qd_data['list'] = $re_data1;
        $re_qd_data['update_url'] = $update_url;
        $this->success('成功',$re_qd_data);
    }
}
